import {
  Card,
  Breadcrumb,
  Form,
  Button,
  Radio,
  Input,
  Upload,
  Space,
  message,
} from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import { Link, useParams, useHistory } from 'react-router-dom';
import styles from './index.module.scss';
import ReactQuill from 'react-quill';
import 'react-quill/dist/quill.snow.css';
import Channel from 'components/Channel';
import { useState, useRef, useEffect } from 'react';
import { useDispatch } from 'react-redux';
import { updateArticle } from 'store/actions';
import { http } from 'utils';
const ArticlePublish = () => {
  const [fileList, setFileList] = useState([]);
  const [maxCount, setMaxCount] = useState(1);
  const fileListRef = useRef([]);
  const dispatch = useDispatch();
  const history = useHistory();
  // 创建表单实例
  // 注意：此处的form是从数组中解构出来的
  const [form] = Form.useForm();
  const params = useParams();
  const isEdit = params.id !== undefined;
  const onUploadChange = (info) => {
    // info.fileList 用来获取当前的文件列表
    const fileList = info.fileList.map((file) => {
      // 刚从本地上传的图片
      if (file.response) {
        return {
          url: file.response.data.url,
        };
      }
      // 已有图片
      return file;
    });
    setFileList(fileList);
    fileListRef.current = fileList;
  };
  const changeType = (e) => {
    const count = e.target.value;
    setMaxCount(count);
    if (count === 1) {
      // 单图，只展示第一张
      const firstImg = fileListRef.current[0];
      setFileList(firstImg === undefined ? [] : [firstImg]);
    } else if (count === 3) {
      // 三图，展示所有图片
      setFileList(fileListRef.current);
    }
  };
  const onFinish = async (values) => {
    //说明：如果选择3图，图片数量必须是3张，否则，后端会当中单图处理
    // 后端根据上传图片数量，来识别是单图或三图
    saveArticles(values, 'add');
  };
  const saveDraft = async () => {
    try {
      const values = await form.validateFields();
      saveArticles(values, 'draft');
    } catch {}
  };
  //复用发布文章
  const saveArticles = async (values, saveType) => {
    //说明：如果选择3图，图片数量必须是3张，否则，后端会当中单图处理
    // 后端根据上传图片数量，来识别是单图或三图
    if (values.type !== fileList.length)
      return message.warning('封面数量与所选类型不匹配');
    const { type, ...rest } = values;
    const data = {
      ...rest,
      //注意：接口会按照上传图片数量来觉得单图或三图
      cover: {
        type,
        images: fileList.map((item) => item.url),
      },
    };
    if (isEdit) {
      data.id = params.id;
    }

    try {
      // true 草稿
      // false 正常发布
      await dispatch(updateArticle(data, saveType === 'add', isEdit));
      const text = isEdit ? '修改' : '发布';
      const showMsg = saveType === 'add' ? `${text}发布成功` : '存入草稿成功';
      message.success(showMsg, 1, () => {
        history.push('/home/article');
      });
    } catch {}
  };
  // 6. 编辑文章
  // 回填数据
  useEffect(() => {
    // 不是编辑状态直接return，不进行数据回填
    if (!isEdit) return;
    (async () => {
      try {
        // 获取文章信息
        const res = await http.get(`/mp/articles/${params.id}`);
        const {
          id,
          title,
          channel_id,
          content,
          cover: { type, images },
        } = res.data.data;
        // 文章数据
        const article = {
          id,
          title,
          channel_id,
          content,
          type,
          images,
        };
        const { images: imgs, ...formValue } = article;
        // 动态设置表单数据
        form.setFieldsValue(formValue);

        // 格式化封面图片数据
        const imageList = imgs.map((item) => ({ url: item }));
        setFileList(imageList);
        setMaxCount(formValue.type);
        fileListRef.current = imageList;
      } catch (error) {
        console.log(error);
      }
    })();
  }, [params.id, isEdit, form]);

  return (
    <div className={styles.root}>
      <Card
        title={
          <Breadcrumb separator=">">
            <Breadcrumb.Item>
              <Link to="/home">首页</Link>
            </Breadcrumb.Item>
            <Breadcrumb.Item>
              {isEdit ? '修改文章' : '发布文章'}
            </Breadcrumb.Item>
          </Breadcrumb>
        }
      >
        <Form
          labelCol={{ span: 4 }}
          wrapperCol={{ span: 16 }}
          initialValues={{ type: 1, content: '' }}
          onFinish={onFinish}
          form={form}
        >
          <Form.Item
            label="标题"
            name="title"
            rules={[
              {
                required: true,
                message: '请输入文章标题',
              },
            ]}
          >
            <Input placeholder="请输入文章标题" style={{ width: 400 }} />
          </Form.Item>
          <Form.Item
            label="频道"
            name="channel_id"
            rules={[
              {
                required: true,
                message: '请选择文章频道',
              },
            ]}
          >
            <Channel width={200} />
          </Form.Item>
          <Form.Item label="封面">
            <Form.Item name="type">
              <Radio.Group onChange={changeType}>
                <Radio value={1}>单图</Radio>
                <Radio value={3}>三图</Radio>
                <Radio value={0}>无图</Radio>
              </Radio.Group>
            </Form.Item>
            {maxCount > 0 && (
              <Upload
                name="image"
                listType="picture-card"
                className="avatar-uploader"
                showUploadList
                action="http://geek.itheima.net/v1_0/upload"
                multiple={maxCount > 1}
                maxCount={maxCount}
                fileList={fileList}
                onChange={onUploadChange}
              >
                <div style={{ marginTop: 8 }}>
                  <PlusOutlined />
                </div>
              </Upload>
            )}
          </Form.Item>
          <Form.Item
            label="内容"
            name="content"
            rules={[{ required: true, message: '请输入文章内容' }]}
          >
            <ReactQuill
              className="publish-quill"
              theme="snow"
              placeholder="请输入文章内容"
            ></ReactQuill>
          </Form.Item>
          <Form.Item wrapperCol={{ offset: 4 }}>
            <Space>
              <Button size="large" type="primary" htmlType="submit">
                {isEdit ? '修改文章' : '发布文章'}
              </Button>
              <Button size="large" onClick={saveDraft}>
                存入草稿
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Card>
    </div>
  );
};
export default ArticlePublish;
